package com.example.visit

import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Intent
import android.widget.DatePicker
import android.widget.TimePicker

import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.VisitEntityItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.base.utils.GlideUtils
import com.example.visit.databinding.ActivityVisitAddBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.util.Calendar

@Route(path = "/visit/VisitAddActivity")
@AndroidEntryPoint
class VisitAddActivity : BaseActivity<ActivityVisitAddBinding,VisitIntent,VisitViewModel>() {
    val imgs = mutableListOf<String>()

    override fun getLayout(): Int  = R.layout.activity_visit_add

    override fun getVM(): Class<VisitViewModel>  = VisitViewModel::class.java

    override fun initView() {
        //点击申请车位的开关 下方车牌号可用状态发生变化
        binding.visitaddSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.visitaddCar.isEnabled = isChecked
        }
        //点击日期图标，弹出日期选择框
        binding.visitaddIvDate.setOnClickListener {
            val calendar = Calendar.getInstance()
            DatePickerDialog(this,object :OnDateSetListener{
                override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                    //将选择后的日期更新到控件上
                    val monthStr = if(month+1<10) "0${month+1}" else month+1
                    val day = if(dayOfMonth<10) "0$dayOfMonth" else dayOfMonth
                    binding.visitaddDate.setText("$year-$monthStr-$day")
                }
            },calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            )
                .show()
        }
        //点击时间图标，弹出时间选择框
        binding.visitaddIvStart.setOnClickListener {
            val calendar = Calendar.getInstance()
            TimePickerDialog(this,object:OnTimeSetListener{
                override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                    val hour = if(hourOfDay<10) "0$hourOfDay" else hourOfDay
                    val minuteStr = if(minute<10) "0$minute" else minute
                    binding.visitaddStart.setText("$hour:$minuteStr:00")
                }
            },calendar.get(Calendar.HOUR),calendar.get(Calendar.MINUTE),true)
                .show()
        }
        binding.visitaddIvEnd.setOnClickListener {
            val calendar = Calendar.getInstance()
            TimePickerDialog(this,object:OnTimeSetListener{
                override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                    val hour = if(hourOfDay<10) "0$hourOfDay" else hourOfDay
                    val minuteStr = if(minute<10) "0$minute" else minute
                    binding.visitaddEnd.setText("$hour:$minuteStr:00")
                }
            },calendar.get(Calendar.HOUR),calendar.get(Calendar.MINUTE),true)
                .show()
        }

        binding.head.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.text = "预约边界"
            headAdd.isVisible = false
            headSave.isVisible = true

            headSave.setOnClickListener{
                val date = binding.visitaddDate.text.toString()
                val time = binding.visitaddStart.text.toString()
                val item = VisitEntityItem(
                    "$date $time",
                    false,
                    imgs,
                    binding.visitaddPeople.text.toString().toInt(),
                    0,
                    binding.visitaddCardId.text.toString(),
                    binding.visitaddPhone.text.toString(),
                    binding.visitaddCar.text.toString(),
                    binding.visitaddPurpose.text.toString(),
                    binding.visitaddSwitch.isChecked,
                    "待审核",
                    binding.visitaddName.text.toString()
                )
                viewModel.sendIntent(VisitIntent.visitAdd(item))
            }

        }
        //点击图片，进行上传
        binding.visitaddIv.setOnClickListener {
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                                ToastUtils.showLong("新增预约成功")
                                finish()
                            }

                            HttpType.UPLOAD -> {
                                ToastUtils.showLong("上传成功")
                                val s = it.data as String
                                val s1 = s.split(":")[1]
                                val url = "http://10.161.9.80:2209/images/visit/${SPUtils.getInstance().getInt("uid")}/$s1"
                                imgs.add(url)
                            }
                            else->{

                            }

                        }
                    }
                    else->{

                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE&& resultCode== RESULT_OK){
            val bean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            GlideUtils.loadNormal(this,bean.path,binding.visitaddIv)
            val path = bean.path
            val fileName = path.split("/").last()
            viewModel.sendIntent(VisitIntent.upload(path,fileName))
        }
    }
}